package com.manli.common.utils.qiniu;

import java.io.*;
import java.util.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import com.manli.common.utils.HttpUtil;
import com.qiniu.storage.model.FileInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 文件上传
 * @author Shensg
 * 2018年1月24日
 */
public class UploadFilesUtil {
	
	public static List<String> loadFileUtils(CommonsMultipartFile files[],HttpServletRequest request,String address) throws IOException{
		BufferedInputStream bufferedInput = null;  
    	BufferedOutputStream bufferedOutput = null;
    	FileOutputStream fos=null;
    	InputStream in = null;
        List<String> list = new ArrayList<String>();  
        // 获取项目的路径  
        ServletContext sc = request.getSession().getServletContext();  
        // 上传位置  
        String path = sc.getRealPath("/") + "/"; // 设定文件保存的目录  
        File ff = new File(path);  
        path=ff.getParent()+address+"/";
        File f = new File(path);  
        if (!f.exists())  
            f.mkdirs();        
        for (int i = 0; i < files.length; i++) {  
            // 获取原始文件名
            String fileName = files[i].getOriginalFilename();  
            System.out.println("原始文件名:" + fileName);  
            // 新文件名  
            String newFileName = UUID.randomUUID() + fileName;  
            if (!files[i].isEmpty()) {  
                try {   
                	byte[] buffer = new byte[1024];  
                     fos = new FileOutputStream(path  
                            + newFileName);  
                    bufferedOutput = new BufferedOutputStream(fos);  
                    in = files[i].getInputStream(); 
                    bufferedInput = new BufferedInputStream(in);  
                    int copySize;  
                    while ((copySize = bufferedInput.read(buffer)) > 0){  
                    	bufferedOutput.write(buffer, 0, copySize);  
                    }
                } catch (Exception e) {  
                    e.printStackTrace();  
                } finally{
                	bufferedOutput.flush();  
                    bufferedOutput.close();  
                    fos.close();  
                    in.close();  
                }
            }  
            System.out.println("上传图片到:" + path + newFileName);  
            list.add(address+"/"+newFileName);  
        }
        return list;
	}
	/**
	 * 七牛 bucketShinehaopic
	 * @param files
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static List<String> loadFileByQiniu4BucketShinehaopic(MultipartFile files[],HttpServletRequest request) throws IOException{
    	InputStream in = null;
        List<String> list = new ArrayList<String>();  
        for (int i = 0; i < files.length; i++) {  
            // 获取原始文件名
            String fileName = files[i].getOriginalFilename();  
            System.out.println("原始文件名:" + fileName);  
            if (!files[i].isEmpty()) {  
                try {     
                    in = files[i].getInputStream(); 
                    list.add(QiniuUploadUtils.uploadFileByStream(QiniuConfig.accessKey, QiniuConfig.secretKey, QiniuConfig.bucketShinehaopic, in, fileName,QiniuConfig.bucketShinehaopicUrlPrefix));
                } catch (Exception e) {  
                    e.printStackTrace();  
                } finally{
                    in.close();  
                }
            }  
        }
        return list;
	}

    public static Map imgUrluploadFile(QueryParamsImgUrlUpload urls) throws Exception{
	    Map map = new HashMap();
	    List<QueryParamsImgUrl> list = new ArrayList<>();
        List<Map> nameList = new ArrayList<>();

        List<QueryParamsImgUrl> queryParamsImgUrls = urls.getUrls();
        if(queryParamsImgUrls.size() == 0){
            map.put("list",list);
            map.put("nameList",nameList);
            return map;
        }

        for(int i=0;i<queryParamsImgUrls.size();i++){
            InputStream in = null;
            try {
                Map rmap = HttpUtil.httpsGetImg(queryParamsImgUrls.get(i).getUrl());
                in = (InputStream)rmap.get("in");
                String[] imgNames = queryParamsImgUrls.get(i).getUrl().split("/");
                String qiniuUrl = QiniuUploadUtils.uploadFileByStream(QiniuConfig.accessKey, QiniuConfig.secretKey, QiniuConfig.bucketShinehaopic, in, imgNames[imgNames.length - 1],QiniuConfig.bucketShinehaopicUrlPrefix);
                queryParamsImgUrls.get(i).setUrl(qiniuUrl);
                list.add(queryParamsImgUrls.get(i));
                Map urlMap = new HashMap();
                String[] fileNames = queryParamsImgUrls.get(i).getUrl().split("/");
                urlMap.put("fileName",fileNames[fileNames.length - 1]);
                urlMap.put("url",queryParamsImgUrls.get(i).getUrl());
                urlMap.put("size",rmap.get("fileSize"));
                urlMap.put("type",rmap.get("type"));
                nameList.add(urlMap);
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }finally {
                in.close();
            }
        }

        map.put("list",list);
        map.put("nameList",nameList);
        return map;
    }

    public static List<String> loadFileByQiniu4tpic(MultipartFile file, HttpServletRequest request) throws IOException{
        InputStream in = null;
        List<String> list = new ArrayList<String>();
//        for (int i = 0; i < files.length; i++) {
            // 获取原始文件名
            String fileName = file.getOriginalFilename();
            System.out.println("原始文件名:" + fileName);
            if (!file.isEmpty()) {
                try {
                    in = file.getInputStream();
                    list.add(QiniuUploadUtils.uploadFileByStream(QiniuConfig.accessKey, QiniuConfig.secretKey, QiniuConfig.bucketShinehaopic, in, fileName,QiniuConfig.bucketShinehaopicUrlPrefix));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally{
                    in.close();
                }
            }
//        }

        return list;
    }

	/**
	 * 保存base64文件
	 * @param
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static List<String> loadBase64FileByQiniu4BucketShinehaopic(String base64Content,String fileName,HttpServletRequest request) throws IOException{
		List<String> list = new ArrayList<String>();  
		list.add(QiniuUploadUtils.uploadFileByBase64(base64Content,QiniuConfig.accessKey, QiniuConfig.secretKey, QiniuConfig.bucketShinehaopic,  QiniuConfig.bucketShinehaopicUrlPrefix));
		return list;
	}

    /**
     * 获取空间文件列表
     */
    public static List<QiNiuFileInfo> getFileList(QueryParamsQiniu queryParamsQiniu){
        List<QiNiuFileInfo> fileInfos = QiniuUploadUtils.getFileList(QiniuConfig.accessKey, QiniuConfig.secretKey, QiniuConfig.bucketShinehaopic,queryParamsQiniu.getPrefix(),"");
        return fileInfos;
    }

    /**
     * 删除空间文件
     */
    public static void deleteFile(QueryParamsFileKey queryParamsQiniu)throws Exception{
        QiniuUploadUtils.deleteFile(QiniuConfig.accessKey, QiniuConfig.secretKey, QiniuConfig.bucketShinehaopic,queryParamsQiniu.getFileKey());
    }

    /**
     * 获取空间文件列表
     */
    public static List<QiNiuFileInfo> getFileListPaged(QueryParamsQiniu queryParamsQiniu){
        List<QiNiuFileInfo> fileInfos = QiniuUploadUtils.getFileListPaged(QiniuConfig.accessKey, QiniuConfig.secretKey, QiniuConfig.bucketShinehaopic,queryParamsQiniu.getPrefix(),"",queryParamsQiniu.getPage(),queryParamsQiniu.getLimit());
        return fileInfos;
    }

}
